package modes

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

/*练习题记录*/
type TopicLogRe struct {
	Id       int64         `json:"tlog_id" xorm:"id"`               //练习题记录id
	UId      int64         `json:"tlog_uid" xorm:"uid"`             //学员ID
	TId      int64         `json:"tlog_tid" xorm:"tid"`             //题id
	SId      int64         `json:"tlog_sid" xorm:"sid"`             //科目id
	CId      int64         `json:"tlog_cid" xorm:"cid"`             //班型
	NId      int64         `json:"exam_nid" xorm:"nid"`             //套题ID
	ExamId   int64         `json:"tlog_exam_id" xorm:"exam_id"`     //考试记录ID
	Answer   string        `json:"tlog_answer" xorm:"answer"`       //答案
	TF       int           `json:"tlog_tf" xorm:"tf"`               //正确错误 0正确 1错误 2半对
	UpdateAt int64         `json:"tlog_update_at" xorm:"update_at"` //更新时间
	At       int64         `json:"tlog_at" xorm:"at"`               //创建时间
	IsLearn  int           `json:"is_learn" xorm:"is_learn"`        //是否学过 0未学过 1已学过
	QId      int64         `json:"qId" xorm:"qid"`                  //分片ID
	Topic    []TopicLibRe  `json:"Topic" xorm:"-"`                  //题
	Text     []TopicTextRe `json:"Text" xorm:"-"`                   //选项

	//  查询字段
	BAt   int64 `json:"-" xorm:"-"` //更新时间开始时间
	EAt   int64 `json:"-" xorm:"-"` //更新时间结束时间
	TType int   `json:"-" xorm:"-"` //题型类型 ：0 全部 1:历年真题;2:章节练习题;3:模拟题

}

func (this *TopicLogRe) TableName() string {
	return "topic_logre"
}
func (this *TopicLogRe) Save() (int64, error) {
	this.At = time.Now().Unix()
	this.UpdateAt = time.Now().Unix()
	return Db(0).Insert(this)
}
func (this *TopicLogRe) SaveList(list []TopicLogRe) error {
	const BatchSize = 100

	items := []TopicLogRe{}
	for _, rId := range list {
		items = append(items, rId)
	}
	for n := 0; ; n++ {
		end := (n + 1) * BatchSize
		if end >= len(items) {
			end -= (end - len(items))
		}

		_, err := Db(0).Table(this).Insert(items[n*BatchSize : end])
		if err != nil {
			return err
		}

		if end >= len(items) {
			break
		}
	}
	return nil

}
func (this *TopicLogRe) Get() (bool, error) {
	return Db(0).Get(this)
}

func (this *TopicLogRe) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *TopicLogRe) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *TopicLogRe) Count(where string) (int64, error) {
	var val Record
	return Db(0).Where(where).Count(&val)
}
func (this *TopicLogRe) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *TopicLogRe) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *TopicLogRe) where(fage, count, page int, where, field string) ([]TopicLogRe, error) {
	list := make([]TopicLogRe, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}

func (this *TopicLogRe) GetList(tidList []int64) ([]int64, error) {
	list := make([]int64, 0)
	err := Db(0).Table(this.TableName()).Select("tid").Asc("tid").In("tid", tidList).Where(fmt.Sprintf(" uid=%d ", this.UId)).Find(&list)
	return list, err
}
func (this *TopicLogRe) GetListByUid() ([]int64, error) {
	list := make([]int64, 0)
	tqIdlist := make([]int64, 0)
	Db(0).SQL(fmt.Sprintf("SELECT id from subject_ques WHERE sid >= %d and sid< %d  and start=0", this.SId-(this.SId%100000), this.SId-(this.SId%100000)+100000)).Find(&tqIdlist)
	nidlist := make([]int64, 0)
	Db(0).Table("toplibnamere").Cols("id").In("tq_id", tqIdlist).Where("state = ?", 0).Find(&nidlist)
	err := Db(0).Table(this.TableName()).In("nid", nidlist).Where("uid=?", this.UId).Cols("tid").Distinct("tid").Find(&list)

	return list, err
}

func (this *TopicLogRe) GetListByExamId() ([]TopicLogRe, error) {
	list := make([]TopicLogRe, 0)
	err := Db(0).Table(this.TableName()).
		Asc("tid").Where(fmt.Sprintf(" uid=%d and exam_id=%d", this.UId, this.ExamId)).Find(&list)
	return list, err
}

type TopicLogReSum struct {
	UpdateAt string `json:"update_at" xorm:"updatetime"` //更新时间
	Num      int64  `json:"num" xorm:"num"`              //创建时间
}

func (this *TopicLogRe) GetTExamlogEX(nidList []int64, dataType int) ([]TopicLogReSum, error) {
	list := make([]TopicLogReSum, 0)
	var dataTypeF = ""
	var selectCol = " COUNT(1) num, "
	var strDataType = ""

	if dataType == 1 {
		strDataType = "'%Y-%c-%d'"
		dataTypeF = " FROM_UNIXTIME(update_at," + strDataType + "  ) "
		selectCol += dataTypeF + "  as updatetime"
	} else if dataType == 2 {
		strDataType = "'%Y-%u'"
		dataTypeF = " FROM_UNIXTIME(update_at," + strDataType + " ) "
		selectCol += dataTypeF + "  as updatetime"

	} else {
		strDataType = "'%Y-%c'"

		dataTypeF = " FROM_UNIXTIME(update_at," + strDataType + " ) "
		selectCol += dataTypeF + "  as updatetime"
	}
	whereadd := fmt.Sprintf(" and nid in (%v)   ", strings.Replace(strings.Trim(fmt.Sprint(nidList), "[]"), " ", ",", -1))
	if this.TType == 0 {
		whereadd = ""
	}
	err := Db(0).SQL(" SELECT  " + selectCol + " FROM `topic_logre`" +
		" WHERE  uid =" + strconv.FormatInt(this.UId, 10) + " and update_at between " + strconv.FormatInt(this.BAt, 10) + " and " + strconv.FormatInt(this.EAt, 10) + " and sid=" + strconv.FormatInt(this.SId, 10) + whereadd + "   " +
		"GROUP BY  FROM_UNIXTIME(update_at," + strDataType + ") ORDER BY  FROM_UNIXTIME(update_at," + strDataType + " ) desc ").Find(&list)
	return list, err
}

func (this *TopicLogRe) UpdateExamId(filed string) (int64, error) {
	where := fmt.Sprintf("uid = %d and nid = %d", this.UId, this.NId)
	i, e := this.update(where, filed)
	return i, e
}

type TopList struct {
	UId int64 `json:"update_at" xorm:"uid"` //更新时间
	CId int64 `json:"update_at" xorm:"cid"` //更新时间
	Nid int64 `json:"update_at" xorm:"nid"` //更新时间
}

func (this *TopicLogRe) GetList22() ([]TopList, error) {
	topLists := make([]TopList, 0)
	err := Db(0).SQL("SELECT uid , cid ,nid from  topic_logre	WHERE exam_id=0	GROUP BY uid , cid ,nid").Find(&topLists)
	return topLists, err
}
